package com.yohann.boot.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ThreadPoolExecutor;

/**
 * 线程池配置
 *
 * @author Yeung Wah
 * @since 2021/5/7
 */
@Slf4j
@Configuration
@EnableCaching
@EnableScheduling
public class ThreadPoolConfig implements AsyncConfigurer {

    @Value("${spring.threadPool.corePoolSize}")
    private Integer corePoolSize;
    @Value("${spring.threadPool.maxPoolSize}")
    private Integer maxPoolSize;
    @Value("${spring.threadPool.queueCapacity}")
    private Integer queueCapacity;
    @Value("${spring.threadPool.threadNamePrefix}")
    private String threadNamePrefix;
    @Value("${spring.threadPool.keepAliveSeconds}")
    private Integer keepAliveSeconds;

    @Bean("threadPool")
    @Override
    public ThreadPoolTaskExecutor getAsyncExecutor() {
        ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
        taskExecutor.setCorePoolSize(corePoolSize);
        taskExecutor.setMaxPoolSize(maxPoolSize);
        taskExecutor.setQueueCapacity(queueCapacity);
        taskExecutor.setThreadNamePrefix(threadNamePrefix);
        taskExecutor.setKeepAliveSeconds(keepAliveSeconds);
        taskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        taskExecutor.initialize();
        return taskExecutor;
    }

    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return (exception, method, params) ->
                log.error("任务启动失败:{},method:{}",
                        exception.getMessage(),
                        method.getClass() + "#" + method.getName());
    }
}